package com.dingxin.ship_together_api.config.mybatis;

import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class CustomizedObjectHandler implements MetaObjectHandler {

    /**
     * 自动填充时间和username
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "createBy", String.class, getCurUser());
        this.strictUpdateFill(metaObject, "updateBy", String.class, getCurUser());
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName( "updateBy", getCurUser(),metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }

    public String getCurUser() {
        try {
            StpUtil.getLoginIdAsString();
        } catch (SaTokenException e) {
            return "system";
        }

        if (StringUtils.isBlank(StpUtil.getLoginIdAsString())) {
            return "system";
        }

        return StpUtil.getLoginIdAsString();
    }
}
